import { View, Text, TouchableOpacity, ScrollView, Image } from 'react-native';
import React, { useState } from 'react';
import { useNavigation } from '@react-navigation/native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useToast } from '../../components/MyToast/useToasr';
import styles from './styles';
import { useCartStore } from '../../store/CartStore';

/**
 * 支付页面组件
 * 展示商品信息、优惠选项、金额明细和支付方式选择
 */
const PayScreen = () => {
  // 仓库中获取购物车数据
  const { cartList } = useCartStore();

  const navigation = useNavigation();
  //   const route = useRoute();
  const toast = useToast();

  // 从路由参数中获取商品信息，如果没有则使用默认值
  const list = cartList.filter(item => item.status);
  const course = list.reduce((total, item) => total + item.price * item.num, 0);

  // 支付方式状态管理
  const [selectedPayment, setSelectedPayment] = useState('alipay');

  // 余额抵扣状态
  const [balanceDeduction, setBalanceDeduction] = useState(true);

  // 计算实际支付金额
  const balanceAmount = 63.23;
  const actualPrice = balanceDeduction ? course - balanceAmount : course;

  /**
   * 处理优惠券点击事件
   */
  const handleCouponPress = () => {
    toast.info('优惠券选择功能尚未实现');
  };

  /**
   * 处理优惠码点击事件
   */
  const handleDiscountCodePress = () => {
    toast.info('优惠码兑换功能尚未实现');
  };

  /**
   * 处理充值按钮点击事件
   */
  const handleRechargePress = () => {
    toast.info('余额充值功能尚未实现');
  };

  /**
   * 处理支付方式选择
   */
  const handlePaymentSelect = (paymentType: string) => {
    setSelectedPayment(paymentType);
  };

  /**
   * 处理提交订单按钮点击事件
   */
  const handleSubmitOrder = () => {
    toast.info('订单提交成功，即将跳转到支付页面');

    // 模拟支付流程，2秒后返回上一页
    setTimeout(() => {
      navigation.goBack();
    }, 2000);
  };

  /**
   * 渲染支付方式选项
   */
  const renderPaymentOption = (
    type: string,
    title: string,
    icon: React.ReactNode,
  ) => {
    const isSelected = selectedPayment === type;

    return (
      <TouchableOpacity
        style={styles.paymentOption}
        onPress={() => handlePaymentSelect(type)}
        activeOpacity={0.7}
      >
        <View style={styles.paymentLeftContent}>
          {icon}
          <Text style={styles.paymentTitle}>{title}</Text>
        </View>
        <View
          style={[styles.radioButton, isSelected && styles.radioButtonSelected]}
        >
          {isSelected && <View style={styles.radioButtonInner} />}
        </View>
      </TouchableOpacity>
    );
  };

  return (
    <SafeAreaView style={styles.container} edges={['top', 'right', 'left']}>
      <ScrollView
        style={styles.scrollView}
        showsVerticalScrollIndicator={false}
      >
        {/* 商品信息区域 */}
        <View style={styles.productInfoContainer}>
          {list.map(item => {
            return (
              <View style={styles.productInfoHeader} key={item.id}>
                <Image
                  source={{ uri: item.cover }}
                  style={styles.productImage}
                />

                <View style={styles.productDetails}>
                  <Text style={styles.productTitle} numberOfLines={2}>
                    {item.title}
                  </Text>
                  <View style={styles.productPriceContainer}>
                    <Text style={styles.productPrice}>
                      ¥{item.price.toFixed(2)}
                    </Text>
                    <Text>数量:{item.num}</Text>
                  </View>
                </View>
              </View>
            );
          })}
        </View>

        {/* 优惠区域 */}
        <View style={styles.discountContainer}>
          <TouchableOpacity
            style={styles.discountItem}
            onPress={handleCouponPress}
            activeOpacity={0.7}
          >
            <Text style={styles.discountLabel}>优惠券</Text>
            <View style={styles.discountValueContainer}>
              <Text style={styles.discountValue}>0张可用</Text>
              <View style={styles.arrowIcon} />
            </View>
            <View style={[styles.checkbox, styles.checkboxUnselected]} />
          </TouchableOpacity>

          <TouchableOpacity
            style={styles.discountItem}
            onPress={handleDiscountCodePress}
            activeOpacity={0.7}
          >
            <Text style={styles.discountLabel}>优惠码</Text>
            <View style={styles.discountValueContainer}>
              <Text style={styles.discountValue}>兑换</Text>
              <View style={styles.arrowIcon} />
            </View>
            <View style={[styles.checkbox, styles.checkboxUnselected]} />
          </TouchableOpacity>

          <Text style={styles.discountNote}>
            同一订单中，优惠码与优惠券只能二选一。
          </Text>
        </View>

        {/* 金额明细区域 */}
        <View style={styles.priceContainer}>
          <View style={styles.priceItem}>
            <Text style={styles.priceLabel}>商品金额</Text>
            <Text style={styles.priceValue}>¥{course.toFixed(2)}</Text>
          </View>

          <View style={styles.priceItem}>
            <Text style={styles.priceLabel}>余额抵扣</Text>
            <View style={styles.balanceContainer}>
              <TouchableOpacity
                onPress={handleRechargePress}
                activeOpacity={0.7}
              >
                <Text style={styles.rechargeText}>充值</Text>
              </TouchableOpacity>
              <Text style={styles.balanceValue}>
                -¥{balanceAmount.toFixed(2)}
              </Text>
              <TouchableOpacity
                style={[styles.switch, balanceDeduction && styles.switchActive]}
                onPress={() => setBalanceDeduction(!balanceDeduction)}
              >
                <View style={styles.switchThumb} />
              </TouchableOpacity>
            </View>
          </View>
        </View>

        {/* 支付方式选择区域 */}
        <View style={styles.paymentContainer}>
          <Text style={styles.sectionTitle}>支付方式</Text>

          {renderPaymentOption(
            'alipay',
            '支付宝',
            <View style={[styles.paymentIcon, styles.alipayIcon]}>
              <Text style={styles.paymentIconText}>支</Text>
            </View>,
          )}

          {renderPaymentOption(
            'wechat',
            '微信支付',
            <View style={[styles.paymentIcon, styles.wechatIcon]}>
              <Text style={styles.paymentIconText}>微</Text>
            </View>,
          )}

          {renderPaymentOption(
            'friend',
            '请朋友代付',
            <View style={[styles.paymentIcon, styles.friendIcon]}>
              <Text style={styles.paymentIconText}>友</Text>
            </View>,
          )}
        </View>

        {/* 底部空间，确保内容不被底部按钮遮挡 */}
        <View style={styles.bottomSpace} />
      </ScrollView>

      {/* 底部提交订单栏 */}
      <View style={styles.submitBar}>
        <View style={styles.submitBarLeft}>
          <Text style={styles.submitBarLabel}>实付</Text>
          <Text style={styles.submitBarPrice}>¥{actualPrice.toFixed(2)}</Text>
        </View>
        <TouchableOpacity
          style={styles.submitButton}
          onPress={handleSubmitOrder}
          activeOpacity={0.8}
        >
          <Text style={styles.submitButtonText}>提交订单</Text>
        </TouchableOpacity>
      </View>
    </SafeAreaView>
  );
};

export default PayScreen;
